package cn.edu.xmist.java.util.vector;

import java.lang.reflect.Field;
import java.util.Vector;

/**
 * @author zhongjinbin 2021/4/9
 * @since 0.0.1
 * vector的扩容demo
 */
public class VectorGrowDemo {
    // 获取vector容量
    public static Integer getCapacity(Vector vector) {
        Integer length = null;
        Class clazz = vector.getClass();
        Field field;
        try {
            field = clazz.getDeclaredField("elementData");
            field.setAccessible(true);
            Object[] object = (Object[]) field.get(vector);
            length = object.length;
            return length;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return length;
    }

    public static void main(String[] args) {
        Vector<Integer> vector1 = new Vector<>();

        /**
         * 获取默认初始容量10
         */
        Integer capacity = getCapacity(vector1);
        int size = vector1.size();
        System.out.println("vector1的容量:" + capacity);
        System.out.println("vector1的大小:" + size);
        System.out.println("----------------------------");

        Vector<Integer> vector2 = new Vector<>(11);

        /**
         * 获取容量,vector初始化容量是11
         */
        capacity = getCapacity(vector2);
        vector2.add(1);
        size = vector2.size();
        System.out.println("vector2的初始容量:" + capacity);
        System.out.println("vector2的大小:" + size);
        System.out.println("----------------------------");

        Vector<Integer> vector3 = new Vector<>(11);

        /**
         * 获取容量,arrayvector初始化容量是10
         */
        capacity = getCapacity(vector3);
        System.out.println("vector3的初始容量:" + capacity);
        for (int i = 0; i < 12; i++) {
            vector3.add(i);
        }
        capacity = getCapacity(vector3);
        size = vector3.size();
        System.out.println("vector3的扩容容量:" + capacity);
        System.out.println("vector3的大小:" + size);
        System.out.println("----------------------------");

        Vector<Integer> vector4 = new Vector<>(11);
        for (int i = 0; i < 12; i++) {
            vector4.add(i);
        }
        capacity = getCapacity(vector4);
        System.out.println("vector4的初始容量:" + capacity);
        size = vector4.size();
        System.out.println("vector4的扩容容量:" + capacity);
        System.out.println("vector4的大小:" + size);
        vector4.remove(vector4.size() - 1);
        capacity = getCapacity(vector4);
        System.out.println("vector4的缩容容量:" + capacity);
        System.out.println("vector4的大小:" + size);
    }
}
